<template>
	<view class="container" style="background: #fff;">
		<form>
			<view>
				<label>收货人:</label>
				<input type="text" v-model="address.userName" placeholder="请输入收货人姓名" />
			</view>
			<view>
				<label>电话:</label>
				<input type="text" v-model="address.phone" placeholder="请输入收货人电话" />
			</view>
			<view>
				<label>收货地址:</label>
				<input type="text" v-model="address.addressName" placeholder="请输入收货地址" />
			</view>
			<view>
				<label>是否默认:</label>
				<switch :checked="address.isDefault" @change="onSwitchChange" />
			</view>

			<button type="submit" @click="handleSubmit()">保存</button>
		</form>
	</view>
</template>

<script>
	export default {

		data() {
			return {
				address: {
					userName: '',
					phone: '',
					addressName: '',
					isDefault: null,
					userId: null
				},
			}
		},
		onLoad(options) {
			this.addressId = options.addressId;
			this.address.userId = options.userId;
			this.getAddressById();

		},
		methods: {
			async getAddressById() {
				try {
					const res = await uni.$http.get(`/wx/addressById/${this.addressId}`);
					const addressData = res.data.data;
					console.log(addressData.isDefault)
					this.address.userName = addressData.userName;
					this.address.phone = addressData.phone;
					this.address.addressName = addressData.addressName;
					this.address.isDefault = addressData.isDefault === true; // 确保是布尔值
				} catch (e) {
					console.log(e);
				}
			},
			onSwitchChange(event) {
				this.address.isDefault = event.detail.value
				console.log('Switch changed to:', event.detail.value);
			},
			async handleSubmit() {
				if (!this.address.userId) {
					console.error('UserId 未定义，无法加载用户信息', this.address.userId);
					return;
				}
				if (!this.address.userName) {
					uni.showToast({
						title: '请填写收货人！',
						icon: 'none'
					});
					return;
				}
				if (!this.address.phone) {
					uni.showToast({
						title: '请填写收货人电话！',
						icon: 'none'
					});
					return;
				}

				if (!this.address.addressName) {
					uni.showToast({
						title: '请填写收货地址！',
						icon: 'none'
					});
					return;
				}
				try {
					console.log('isDefault:', this.address.isDefault);
					const res = await uni.$http.post('/wx/addressSave', this.address);
					console.log(res.data)

				} catch (error) {
					console.error('Error adding address:', error);
				}
			}
		}
	};
</script>

<style lang="scss">
	.container {
		padding: 20px;
	}

	label {
		font-size: 16px;
		margin-right: 10px;
	}

	input,
	{
	margin-bottom: 10px;
	border: 1px solid #ccc;
	padding: 5px;
	}

	button {
		width: 250px;
		height: 40px;
		// padding: 5px 5px;
		margin-top: 10px;
		background-color: #409EFF;
		color: white;
		border-radius: 10px;
	}
</style>